/**
 * @license Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved.
 * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
 */

/**
 * @fileOverview Increase and Decrease Indent commands.
 */

(function() {
    'use strict';

    var TRISTATE_DISABLED = CKEDITOR.TRISTATE_DISABLED,
        TRISTATE_OFF = CKEDITOR.TRISTATE_OFF;

    CKEDITOR.plugins.add('textindentall', {
        lang: 'en,pt-br,zh-cn',
        // jscs:enable maximumLineLength
        icons: 'textindentall', // %REMOVE_LINE_CORE%
        hidpi: true, // %REMOVE_LINE_CORE%
        init: function(editor) {
            var indentation = editor.config.indentation;
            var indentationKey = editor.config.indentationKey;
            var editable = editor.editable();

            if(typeof(indentation) == 'undefined')
                indentation = '2em';
            if(typeof(indentationKey) == 'undefined')
                indentationKey = 'tab';

            if( indentationKey !== false){
                editor.on('key', function(ev) {
                    if(ev.data.domEvent.$.key.toLowerCase() === indentationKey.toLowerCase().trim() || ev.data.keyCode === indentationKey){
                        editor.execCommand('textindentall');
                        ev.cancel();  
                    }
                });
            }
            editor.addCommand('textindentall', {
                allowedContent: 'p{text-indent}',
                requiredContent: 'p',
                exec: function(evt) {
                    var editable = editor.editable();
                    if (editable.is('textarea')) {
                      var textarea = editable.$;

                      if (CKEDITOR.env.ie && textarea.createTextRange) {
                        textarea.createTextRange().execCommand('SelectAll');
                      } else {
                        textarea.selectionStart = 0;
                        textarea.selectionEnd = textarea.value.length;
                      }

                      textarea.focus();
                    } else {
                      if (editable.is('body'))
                        editor.document.$.execCommand('SelectAll', false, null);
                      else {
                        var range = editor.createRange();
                        range.selectNodeContents(editable);
                        range.select();
                      }

                      // Force triggering selectionChange (https://dev.ckeditor.com/ticket/7008)
                      editor.forceNextSelectionCheck();
                      editor.selectionChange();
                    }

                    var style_textindente = new CKEDITOR.style({
                        element: 'p',
                        styles: { 'text-indent': indentation},
                        overrides: [{
                            element: 'text-indent', attributes: { 'size': '0'}
                        }]
                    });

                    var style_no_textindente = new CKEDITOR.style({
                        element: 'p',
                        styles: { 'text-indent': '0' },
                        overrides: [{
                            element: 'text-indent', attributes: { 'size': indentation}
                        }]
                    });
                    editor.getCommand('textindent').setState(CKEDITOR.TRISTATE_OFF);
                    if( style_textindente.checkActive(editor.elementPath(), editor) ){
                        editor.fire('saveSnapshot');
                        editor.applyStyle(style_no_textindente);
                        editor.getCommand('textindentall').setState(CKEDITOR.TRISTATE_OFF);
                    }
                    else{
                        editor.fire('saveSnapshot');
                        editor.applyStyle(style_textindente);
                        editor.getCommand('textindentall').setState(CKEDITOR.TRISTATE_ON);
                    }

                    // var range = editor.getSelection().getRanges()[0];

                    // var walker = new CKEDITOR.dom.walker(range),
                    //     node;
                    // var state = editor.getCommand('textindentall').state;

                    // while ((node = walker.next())) {
                    //   if (node.type == CKEDITOR.NODE_ELEMENT) {
                    //     if (node.getName() === "p") {
                    //       editor.fire('saveSnapshot');
                    //       if (state == CKEDITOR.TRISTATE_ON) {
                    //         node.removeStyle("text-indent");
                    //         editor.getCommand('textindentall').setState(CKEDITOR.TRISTATE_OFF);
                    //         editor.getCommand('textindent').setState(CKEDITOR.TRISTATE_OFF);
                    //       } else {
                    //         node.setStyle("text-indent", indentation);
                    //         editor.getCommand('textindentall').setState(CKEDITOR.TRISTATE_ON);
                    //         editor.getCommand('textindent').setState(CKEDITOR.TRISTATE_OFF);
                    //       }
                    //     }
                    //   }
                    // }

                    // if (node === null) {

                    //   node = editor.getSelection().getStartElement().getAscendant('p', true);

                    //   editor.fire('saveSnapshot');

                    //   if (state == CKEDITOR.TRISTATE_ON) {
                    //     node.removeStyle("text-indent");
                    //     editor.getCommand('textindentall').setState(CKEDITOR.TRISTATE_OFF);
                    //   } else {
                    //     node.setStyle("text-indent", indentation);
                    //     editor.getCommand('textindentall').setState(CKEDITOR.TRISTATE_ON);
                    //   }
                    // }
                }
            });
            // Create and register toolbar button if possible.
            if (editor.ui.addButton) {
              editor.ui.addButton('TextindentAll', {
                label: editor.lang.textindentall.labelName,
                command: 'textindentall',
                directional: true,
                toolbar: 'textindent,10',
              });
            }
        }
    });
})();